<!--  
  @name: 首页
  @date: 2019.12.25
 -->
<template>
	<view class="content">
		<nav-title
			title="车用尿素"
			:backHome="true"
			:blackTheme="true"
			backgroundColor="#fff"
		></nav-title>
		<!-- 地图组件 -->
		<map
			id="theMap"
			style="width: 750rpx; height: 100vh;"
			show-location
			:latitude="latitude"
			:longitude="longitude"
			:markers="fsList"
			:scale="10"
			@markertap="markerTap"
			@regionchange="regionchange"
			@tap="clickMap"
		/>

		<!-- 定位按钮 -->
		<view
			class="locate-btn"
			@tap="
				isClickLoca = true;
				getLocation();
			"
		></view>

		<view
			class="information"
			@touchstart="test.touchStartsHandle"
			@touchmove="test.touchMoveHandle"
			@touchend="test.touchEndHandle"
			@scrolltoupper="test.scrolltoupperHandle"
			:class="infoHeight === 1 ? 'h1' : 'h2'"
			:data-clientH="clientH"
		>
			<!-- 触摸滑动 -->
			<view class="touch-view">
				<!-- 上拉按钮 -->
				<view class="pull-up-down" @tap="setInfoHeight(infoHeight == 1 ? 1 : 2)">
					<view :class="infoHeight === 1 ? 'icon-1' : 'icon-2'"></view>
				</view>
				<!-- 设置、扫码、个人 -->
				<view class="menu">
					<view class="item">
						<image
							class="setting"
							src="http://img.etubang.com/group1/M00/00/49/rBCky1_HJhyANzeEAAAOB8wWS9I983.png"
							@tap="$showToast('功能开发中，敬请期待')"
						></image>
						<view class="note" v-show="infoHeight === 1">售后服务</view>
					</view>
					<view class="item ">
						<view class="scan">
							<image
								class=""
								src="http://img.etubang.com/group1/M00/00/49/rBCky1_HJjqAfW9kAAAGL1frLBc903.png"
								@tap="
									clearTimer();
									scanCode();
								"
							></image>
							<text>扫码</text>
						</view>
					</view>
					<view class="item">
						<image
							class="user"
							src="http://img.etubang.com/group1/M00/00/49/rBCky1_HJkuADs5sAAAO6NJokP0814.png"
							@tap="
								clearTimer();
								goUser();
							"
						></image>
						<view class="note" v-show="infoHeight === 1">个人中心</view>
					</view>
				</view>
			</view>

			<!-- 分隔线 -->
			<view class="line" v-show="infoHeight === 2"></view>

			<!-- 加注站列表 -->
			<scroll-view class="fs-list" scroll-y @scroll="test.scrollHandle">
				<view class="fs-no-list" v-if="fsList.length === 0">200公里内暂无加注站</view>
				<view class="list" v-for="(item, index) in fsList" :key="item.siteId">
					<view
						class="msg"
						@tap="
							clearTimer();
							$navigateTo('/pagesUc/site/index?siteId=' + item.siteId);
						"
					>
						<view class="name text_over">{{ item.siteName }}</view>
						<view class="brand text_over">
							尿素品牌：
							<text v-text="item.siteBrand ? item.siteBrand : '--'"></text>
						</view>
						<view class="more" @tap.stop="callPhone(item, index)">
							<view class="icon"></view>
							<text
								class="text"
								v-text="item.contactPhone ? item.contactPhone : '--'"
							></text>
						</view>
					</view>
					<view class="nav">
						<view
							class="navi"
							@click="
								clearTimer();
								$navStart(item.latitude, item.longitude);
							"
						></view>
						<view class="navt">{{ item.distance }}KM</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 点击标记点后出现的信息弹窗 -->
		<view class="fs-info" v-show="markersInfoShow">
			<view
				class="go"
				@tap="
					clearTimer();
					$navigateTo('/pagesUc/site/index?siteId=' + fsInfo.siteId);
				"
			>
				站点
				<br />
				详情
			</view>
			<view class="msg">
				<view class="name text_over">{{ fsInfo.siteName }}</view>
				<view class="brand text_over">尿素品牌：{{ fsInfo.siteBrand }}</view>
			</view>
			<view
				class="icon"
				@tap="
					clearTimer();
					$navStart(fsInfo.latitude, fsInfo.longitude);
				"
			></view>
		</view>
		<!-- 登录提示 -->
		<sign-in @submit="reLogin"></sign-in>
		
	</view>
</template>
<script module="test" lang="wxs">
var touchStartY = 0;
var windowHeight = 0;
var curHeight = 0;
var scrollLock = false; // 滚动锁
var scrollTop = 0;

function touchStartsHandle(e,ins) {

	ins.selectComponent('.information').removeClass('h2');
	touchStartY = e.changedTouches[0].clientY;
	var instance = ins.selectComponent('.information');
	windowHeight = instance.getDataset().clienth;
	curHeight = instance.getComputedStyle(['height']).height;
	curHeight = Number(parseFloat(curHeight));
	instance.setStyle({
		"height": curHeight+'px',
	})
}
function touchMoveHandle(e,ins) {
	var clientY = e.changedTouches[0].clientY;
	var delta = touchStartY - clientY;
	ins.selectComponent('.information').removeClass('h1').removeClass('h2');
	if(!scrollLock) {
		ins.selectComponent('.information').setStyle({
			"height": (curHeight + delta)+'px',
		})
	}
}
function touchEndHandle(e,ins) {
	var endY = e.changedTouches[0].pageY;
	var line = endY - touchStartY;
	var tempNum = 0;
	if (line >= 30 && !scrollLock) {
		tempNum = 2;
		ins.selectComponent('.information').addClass('h1');

	} else if (line <= -30 && !scrollLock) {
		tempNum = 1;
		ins.selectComponent('.information').addClass('h2');
		// scrollLock = true; // 滚动锁
	}
	curHeight = 0;

	tempNum && ins.callMethod('setInfoHeight',tempNum);
}
function scrollHandle(e,ins) {

	scrollTop = e.detail.scrollTop;
	var deltaY = e.detail.deltaY;

	if(deltaY<0){
		scrollLock = true;
	} else if (scrollTop < 10) {
		scrollLock = false;
	} else {
		scrollLock = true;
	}
	return false;
}
function scrolltoupperHandle(e,ins) {
	scrollLock = false;
}

module.exports = {
	touchMoveHandle:touchMoveHandle,
	touchStartsHandle:touchStartsHandle,
	touchEndHandle:touchEndHandle ,
	scrollHandle:scrollHandle,
	scrolltoupperHandle:scrolltoupperHandle
}
</script>

<script>
export default {
	components: {},
	data() {
		return {
			theMap: null, //地图map对象
			markerIndex: -1, //点击的标记点index
			markerWd: 28, //标记点icon宽度
			markerHe: 37.5, //标记点icon高度
			infoHeight: 1, //detail区域位置，1则在底部，2则在高处
			fsList: [], //加注站列表数组
			fsInfo: {}, //加注站信息
			markersInfoShow: false, //是否显示marker信息
			touchStartY: 0, //信息区触摸上滑起始竖坐标
			latitudeDef: 0, //打开小程序时初始化的纬度，当用户移动距离超过200km时，将此字段进行更新
			longitudeDef: 0, //打开小程序时初始化的经度，当用户移动距离超过200km时，将此字段进行更新
			timer: null, //定时器，用于实时获取用户地理位置
			isOnShow: false, //是否为第二次以上打开此页面
			isClickLoca: false //是否点击定位按钮
		};
	},
	computed: {
		//登录状态
		isLogin() {
			return this.$store.state.isLogin;
		},
		//位置纬度
		latitude() {
			return this.$store.state.location.latitude;
		},
		//位置经度
		longitude() {
			return this.$store.state.location.longitude;
		},
		clientH() {
			return uni.getSystemInfoSync().windowHeight;
		}
	},
	onLoad() {
		console.log(uni.getSystemInfoSync().windowHeight);
	},
	onShow() {
		if (this.isOnShow) {
			this.clearTimer();
			this.getLocation();
		} else {
			this.isOnShow = true;
		}
		this.timer = setInterval(() => {
			this.getLocation();
		}, 120000);
		// this.$forceUpdate();
		
	},
	onReady() {
		//实例化组图map组件
		this.theMap = uni.createMapContext('theMap');
		this.getLocation();

		console.log(this.$encode('4546465456'));
		console.log(
			this.$decode('GLyFkSZSybYvKboBjiANGz3vZyiZQeviQdKQo3joTzbcaCbCSInTY9QByDTc9fsQ')
		);
	},
	onUnload() {
		this.clearTimer();
	},
	methods: {
		//登录成功
		reLogin() {
			uni.showToast({
				mask: true,
				icon: 'loading',
				title: '加载中...',
				duration: this.$tmp.TIME_SUC
			});
		},
		//清除定时器
		clearTimer() {
			if (this.timer) clearInterval(this.timer);
		},
		//前往个人中心页
		goUser() {
			this.$navigateTo('/pagesUc/user/index');
		},
		//扫码
		scanCode() {
			if (this.isLogin) {
				uni.scanCode({
					success: res => {
						console.log('扫描结果', res);
						if (res.path) {
							this.$navigateTo('/' + res.path);
						} else {
							let url = res.result;
							let idx = url.indexOf('?');
							// 解密参数
							let params = this.$decode(url.substr(idx + 1));
							// 序列化为json
							const obj = this.$urlTojson('?' + params);
							let path = `/pages/fill/fill?macCode=${obj.macCode}&promoteCode=${
								obj.promoteCode
							}`;
							if (obj.macCode) {
								this.$navigateTo(path);
							} else {
								this.$showToast('二维码无效！');
							}
						}
					}
				});
			} else {
				this.$store.commit('showLogin', true);
			}
		},
		//拨打电话
		callPhone(item, index) {
			if (item.contactPhone) {
				this.clearTimer();
				this.$callTel(item.contactPhone);
			}
		},
		//获取周围的加注站
		getFillStatin() {
			this.$http({
				url: this.$api.siteUrl + 'getfillsitelist',
				data: {
					userLat: this.latitudeDef,
					userLng: this.longitudeDef
				},
				loading: 0
			}).then(res => {
				let arr = res;
				arr.forEach((item, index) => {
					item = this.convert2TecentMap(item);
					item.id = index + 1;
					item.width = this.markerWd;
					item.height = this.markerHe;
					item.latitude = parseFloat(item.siteLat);
					item.longitude = parseFloat(item.siteLng);
					item.iconPath = '/static/wxImage/location.png';
					item.distance = this.$mapDistance(
						item.latitude,
						item.longitude,
						this.latitude,
						this.longitude
					);
				});
				this.fsList = [];
				this.fsList = this.fsList.concat(arr);
			});
		},
		//上拉/下拉detail
		setInfoHeight(idx) {
			if (idx === 1) {
				this.infoHeight = 2;
			} else {
				this.infoHeight = 1;
			}
			this.clickMap();
		},
		//点击地图，关闭信息框，缩小标记点等
		clickMap() {
			if (this.markerIndex >= 0) {
				this.fsList[this.markerIndex].width = this.markerWd;
				this.fsList[this.markerIndex].height = this.markerHe;
				this.markerIndex = -1;
			}
			this.markersInfoShow = false;
		},
		//点击标记点
		markerTap(e) {
			let index = this.fsList.findIndex(item => item.id === e.markerId);
			//若是初次点击
			if (index !== this.markerIndex) {
				this.fsInfo = this.fsList[index];
				this.markersInfoShow = true;
				//先把点击点放大
				this.fsList[index].width = this.markerWd * 1.5;
				this.fsList[index].height = this.markerHe * 1.5;
				//再把现有变大的缩小
				if (this.markerIndex >= 0) {
					this.fsList[this.markerIndex].width = this.markerWd;
					this.fsList[this.markerIndex].height = this.markerHe;
				}
				//再重新赋值markerIndex
				this.markerIndex = index;
			}
			//若是重复点击
			else {
				this.clickMap();
			}
		},
		//地图视野变化，缩放或者移动
		regionchange(e) {
			if (e.type === 'begin') return;
			let {
				region: { northeast, southwest },
				centerLocation
			} = e.target;
			let distance1 = this.$mapDistance(
				northeast.latitude,
				northeast.longitude,
				this.latitudeDef,
				this.longitudeDef
			);
			let distance2 = this.$mapDistance(
				southwest.latitude,
				southwest.longitude,
				this.latitudeDef,
				this.longitudeDef
			);
			if (distance1 >= 200 || distance2 >= 200) {
				this.latitudeDef = centerLocation.latitude;
				this.longitudeDef = centerLocation.longitude;
				this.getFillStatin();
			}
		},
		//获取当前位置
		getLocation() {
			uni.getLocation({
				type: 'gcj02',
				success: res => {
					this.theMap.moveToLocation(); //将地图中心移动到当前定位点
					this.$store.commit('setLocation', res);
					this.clickMap();
					if (!this.isOnShow) {
						//初次打开页面(初始化)
						this.latitudeDef = res.latitude;
						this.longitudeDef = res.longitude;
						this.getFillStatin();
					} else {
						//再次回到这个页面
						let distance = this.$mapDistance(
							res.latitude,
							res.longitude,
							this.latitudeDef,
							this.longitudeDef
						);
						//当用户移动距离超过200km或者点击定位按钮时，更新相关数据
						if (distance >= 200 || this.isClickLoca) {
							this.latitudeDef = res.latitude;
							this.longitudeDef = res.longitude;
							if (this.isClickLoca) {
								this.isClickLoca = false;
							}
							this.getFillStatin();
						}
					}
				},
				fail: () => {
					uni.showModal({
						content: '获取位置信息失败，请检查是否打开位置授权',
						showCancel: false,
						success: rs => {
							if (rs.confirm) {
								//#ifdef MP-WEIXIN
								wx.openSetting({});
								//#endif
							}
						}
					});
				}
			});
		},
		convert2TecentMap(obj) {
			if (obj.siteLng == '' && obj.siteLat == '') {
				return obj;
			}
			var x_pi = (3.14159265358979324 * 3000.0) / 180.0;
			var x = obj.siteLng - 0.0065;
			var y = obj.siteLat - 0.006;
			var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
			var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
			var qqlng = z * Math.cos(theta);
			var qqlat = z * Math.sin(theta);
			obj.siteLng = qqlng;
			obj.siteLat = qqlat;
			return obj;
		}
	}
};
</script>

<style lang="scss">
/* 定位按钮 */
.content {
	overflow: hidden;
}
.locate-btn {
	position: fixed;
	right: 26rpx;
	bottom: 448rpx;
	width: 118rpx;
	height: 118rpx;
	z-index: $z-index-public;
	background-image: url(http://img.etubang.com/group1/M00/00/49/rBCky1_HJ9eAQ1JpAAAg8E7Hb34704.png);
}

/* 底部搜索详情等区域 */
.information {
	position: fixed;
	bottom: 0;
	left: 30rpx;
	right: 30rpx;
	width: 690rpx;
	background-color: $color-white;
	border-radius: $border-radius-bm $border-radius-bm 0 0;
	z-index: $z-index-fixed;
	transition: 0.3s;
	box-shadow: $box-shadow;
	.line {
		width: 100%;
		border-top: $spacing-col solid $color-bg;
	}
}
.information.h1 {
	height: 285rpx !important;
}
.information.h2 {
	height: calc(100vh - 180rpx) !important;
}
.touch-view {
	display: flex;
	flex-direction: column;
}

/* 上拉/下拉按钮 */
.pull-up-down {
	width: 100%;
	height: 86rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	.icon-1,
	.icon-2 {
		width: 90rpx;
		height: 20rpx;
		background-image: url(http://img.etubang.com/group1/M00/00/49/rBCky1_HJoaAfgIPAAACv8U6zkE874.png);
	}
	.icon-2 {
		transform: rotate(180deg);
	}
}

/* 设置、扫码、个人区域 */
.menu {
	width: 100%;
	height: 214rpx;
	display: flex;
	flex-direction: row;
	.item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		.user,
		.setting {
			width: 80rpx;
			height: 80rpx;
		}

		.scan {
			width: 150rpx;
			height: 150rpx;
			background: linear-gradient(-52deg, #2eba6a, #47de88);
			border-radius: 50%;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			box-shadow: 0 1rpx 6rpx 0rpx #2eba6a;
			transform: translateY(-30rpx);
			position: relative;

			> image {
				width: 60rpx;
				height: 60rpx;
			}

			> text {
				color: #ffffff;
				transform: translateY(10rpx);
				font-weight: 600;
			}
		}

		.note {
			color: $color-primary;
			font-size: 22rpx;
			margin-top: 12rpx;
		}
	}
}

/* 加注站列表 */
.fs-list {
	width: 100%;
	height: calc(100vh - 310rpx);
	// padding: 0 35rpx;
	.list {
		padding: 30rpx;
		margin: 0 35rpx;
		margin-top: $spacing-col;
		box-shadow: $box-shadow;
		border-radius: $border-radius-bm;
		display: flex;
		flex-direction: row;
	}
	.list:last-child {
		margin-bottom: 200rpx;
	}
	.msg {
		flex: 1;
		display: inline-block;
		padding-right: 20rpx;
	}
	.name {
		font-size: 30rpx;
		font-weight: bold;
	}
	.brand {
		color: #4d4d4d;
		margin-top: 23rpx;
	}
	.more {
		margin-top: 29rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		.icon {
			width: 32rpx;
			height: 32rpx;
			background-image: url('http://img.etubang.com/group1/M00/00/3F/rBCky14UAQWAJ_C7AAADzUD-bNE403.png');
		}
		.text {
			margin-left: 16rpx;
			color: $color-grey-dark;
			font-size: 30rpx;
		}
	}
	.nav {
		text-align: center;
		padding-top: 15rpx;
	}
	.navi {
		width: 86rpx;
		height: 86rpx;
		background-image: url('http://img.etubang.com/group1/M00/00/3F/rBCky14UASqAH_25AAAOm9xqXI8646.png');
	}
	.navt {
		margin-top: 10rpx;
		font-size: 26rpx;
		color: $color-grey-dark;
		font-family: $font-family-num;
	}
}
.fs-no-list {
	width: 100%;
	margin-top: 100rpx;
	text-align: center;
	color: $color-grey;
}

/* 点击标记点后出现的信息弹窗 */
.fs-info {
	display: flex;
	flex-direction: row;
	position: fixed;
	top: 170rpx;
	left: 62rpx;
	width: 582rpx;
	height: 120rpx;
	z-index: $z-index-public;
	background-color: $color-white;
	border-radius: $border-radius-sm;
	box-shadow: $box-shadow;
	.go {
		display: inline-block;
		width: 124rpx;
		height: 120rpx;
		color: $color-white;
		padding-top: 24rpx;
		text-align: center;
		background-color: $color-green;
		border-radius: $border-radius-sm 0 0 $border-radius-sm;
	}
	.msg {
		display: inline-block;
		flex: 1;
		height: 120rpx;
		padding-left: 35rpx;
		padding-right: 20rpx;
	}
	.name {
		margin-top: 14rpx;
	}
	.brand {
		color: $color-grey-dark;
		margin-top: 16rpx;
		font-size: 24rpx;
	}
	.icon {
		width: 62rpx;
		height: 61rpx;
		margin-top: 30rpx;
		margin-right: 44rpx;
		background-image: url('http://img.etubang.com/group1/M00/00/3F/rBCky14UATeAcMELAAAIuAo_ROc496.png');
	}
}
</style>
